import axios from 'axios';
import config from '../config'
import {  ElMessage, ElLoading } from 'element-plus'
// @ts-ignore
import store from "store"
// import router from '../router'
import {useRouter} from 'vue-router'
const router = useRouter()
// import * as constants from "constants";
const service = axios.create({
    baseURL: config.server,
    timeout: 10000, // 请求超时时间
    headers: {
        'Content-Type': 'application/json;charset=utf-8',
    }
})

// 请求拦截器
service.interceptors.request.use(
    config => {
        // 在发送请求之前做些什么
        return config
    },
    error => {
        // 处理请求错误
        // @ts-ignore
        tell.error(error)
        return Promise.reject(error)
    }
)

// 响应拦截器
service.interceptors.response.use(
    response => {
        // 对响应数据做些什么
        return response.data
    },
    error => {
        // 处理响应错误
        // @ts-ignore
        tell.error(error)
        return Promise.reject(error)
    }
)


// 封装请求方法
function request(r:any) {
    if(store.get('token')){
        service.defaults.headers.common['Authorization'] = 'Bearer ' + store.get('token')
    }
    return new Promise((resolve, reject) => {
        let loading:Object
        if (r.loading){
            loading = ElLoading.service({
                lock: true,
                text: 'Loading',
                background: 'rgba(0, 0, 0, 0.7)',
            })
        }
        r.method = r.method.toUpperCase()          //!!所有请求方法换成大写!!
        let params = {}
        if (r.method === 'GET'){
            params = r.data
        }
        // @ts-ignore
        tell.log('【请求】',r.method, r.url, params, r.data)
        service({
            method: r.method,
            url: r.url,
            params:params,
            data:r.data
        }).then( (res:any)=>{
            res.code = parseInt(res.code)
            // @ts-ignore
            tell.log('【响应】',res)
            if (res.code === 200){
                resolve(res)
            }
            else if (res.code === 401){
                store.clearAll()
                // @ts-ignore
                // router.push({name: 'login'})
                // router.push({ name: 'login' })
                window.location.href = '/login'
            }
            else if (res.code === 444){
                ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
                store.clearAll()
                router.push({ name: 'login' })
            }
            else{
                ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
                reject(res)
            }
        }).catch( (err) => {
            ElMessage({
                message: '内部服务器错误，请稍后再试',
                type: 'warning',
            })
            reject(err)
        }).finally( ()=>{
            if (r.loading) { // @ts-ignore
                loading.close()
            }
        })
    });
}

export default request